package com.apes.framework.plugin.soe.core.utils;

import com.apes.framework.util.MapUtil;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

/**
 * 功能：脚本执行器
 *
 * @author xul
 * @create 2018-09-21 17:33
 */
public class ScriptEvaluator {

    private static ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    private ScriptEvaluator() {
    }

    public static Boolean evalBool(String script, Map input) throws ScriptException {
        Object result = eval(script, input);
        if (result instanceof Boolean) {
            return ((Boolean) result);
        } else if (result instanceof Number) {
            return ((Number) result).doubleValue() > 0;
        }
        return false;
    }

    /**
     * 使用：eval(" a == 1 && b == 4", MapUtil.mapper("a", 1, "b", 4))
     */
    public static Object eval(String script, Map input) throws ScriptException {
        Bindings bindings = engine.createBindings();
        bindings.putAll(input);
        return engine.eval(script, bindings);
    }


}
